package com.prodog.database.loader;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.prodog.database.annotation.Config;
import com.prodog.utils.bean.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@Component
@Slf4j(topic = "游戏配置加载器")
@Order(2)
public class GameConfigLoader implements CommandLineRunner {
    @Value("${game.rootPath}")
    private String gameRootPath;

    @Override
    public void run(String... args) {
        this.scanConfigs();
    }

    private void scanConfigs() {
        log.info("正在加载游戏配置.........");
        //获取所有wrapper
        List<Object> configObjs = SpringBeanUtils.getBeansByAnnotation(Config.class);
        //设置wrapper的属性值
        for (Object config : configObjs) {
            loadConfig(config);
        }
        log.info("游戏配置加载完毕！");
    }

    private void loadConfig(Object config) {
        Config configAno = config.getClass().getAnnotation(Config.class);
        String path = configAno.path();
        String module = configAno.module();
        File configFile = new File(gameRootPath, path);

        String jsonStr = FileUtil.readUtf8String(configFile);
        Map<String, Object> jsonData = JSONUtil.toBean(jsonStr, Map.class);
        Class clz = config.getClass();
        jsonData.forEach((k, v) -> {
            try {
                Field field = clz.getDeclaredField(k);
                if (field != null) {
                    field.setAccessible(true);
                    field.set(config, v);
                }
            } catch (Exception e) {
            }
        });
        log.info("  [" + module + "]加载完成！");
    }

}
